// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'
const store = createStore({
// #endif
	// 单一状态树，定义应用状态的默认初始值，页面显示所需的数据从该对象中进行读取。
	state: {
		hasLogin: false,//是否登录
		isUniverifyLogin: false,//是否一键登录
		loginProvider: "",//登录方式
		openid: null,
		colorIndex: 0,
		colorList: ['#FF0000', '#00FF00', '#0000FF'],
		noMatchLeftWindow: true,
		active: 'componentPage',
		leftWinActive: '/pages/component/view/view',
		activeOpen: '',
		menu: [],
		univerifyErrorMsg: ''
	},
	// 同步操作,用于将数据信息写在全局数据状态中缓存
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setColorIndex(state, index) {
			state.colorIndex = index
		},
		setMatchLeftWindow(state, matchLeftWindow) {
			state.noMatchLeftWindow = !matchLeftWindow
		},
		setActive(state, tabPage) {
			state.active = tabPage
		},
		setLeftWinActive(state, leftWinActive) {
			state.leftWinActive = leftWinActive
		},
		setActiveOpen(state, activeOpen) {
			state.activeOpen = activeOpen
		},
		setMenu(state, menu) {
			state.menu = menu
		},
		setUniverifyLogin(state, payload) {
			typeof payload !== 'boolean' ? payload = !!payload : '';
			state.isUniverifyLogin = payload;
		},
		setUniverifyErrorMsg(state,payload = ''){
			state.univerifyErrorMsg = payload
		}
	},
	// 将state中的数据经过某种变化
	getters: {
		currentColor(state) {
			return state.colorList[state.colorIndex]
		}
	},
	// 异步操作,用于向后台提交数据或者接受后台的数据,通过mutation来改变state而不是直接变更状态。
	actions: {
		// lazy loading openid
		getUserOpenId: async function({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login')
							setTimeout(function() { //模拟异步请求服务器获取 openid
								const openid = '123456789'
								console.log('uni.request mock openid[' + openid + ']');
								commit('setOpenid', openid)
								resolve(openid)
							}, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		},
		getPhoneNumber: function({
			commit
		}, univerifyInfo) {
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/univerify-login',
					method: 'POST',
					data: univerifyInfo,
					success: (res) => {
						const data = res.data
						if (data.success) {
							resolve(data.phoneNumber)
						} else {
							reject(res)
						}

					},
					fail: (err) => {
						reject(res)
					}
				})
			})
		},
		request: function({}, options) {
			var user = uni.getStorageSync('USER');
			var token = user ? user.remember_token : '';
			var showLoading = options.showLoading || false;
			var showModal = options.showModal || false;
			
			//用户交互:加载圈
			if (showLoading) {
				uni.showLoading({title:'加载中...'});
			}
			console.log("网络请求start");
			//网络请求
			return new Promise((resolve, reject) => {
				uni.request({
					url: 'https://bengbu.link/v1/' + options.url,
					method: options.method,
					data: options.data,
					header: {
						"content-type": "application/json",
						"authorization": "Bearer " + token
					},
					success: (res) => {
						console.log("网络请求success:" + JSON.stringify(res));
						//api错误
						if (res.statusCode && res.statusCode != 200) {
							uni.showModal({
								content:"" + res.errMsg
							});
							return;
						}
						
						//返回结果码code判断:0成功,1错误,-1未登录
						if (!res.data.code) {
							if (showModal) {
								uni.showModal({
									showCancel: false,
									content: res.data.message
								});
							}
							// resolve调用后，即可传递到调用方使用then或者async+await同步方式进行处理逻辑
							resolve(res.data)
						} else{
							if (res.data.code == "-1") {
								// 跳转到登录页
								return;
							}
							
							if (res.data.code != "0") {
								uni.showModal({
									showCancel:false,
									content:"" + res.data.message
								});
							}
							// reject调用后，即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
							reject(res.data)
						}
						//typeof param.success == "function" && param.success(res.data);
					},
					fail: (res) => {
						console.log("网络请求fail:" + JSON.stringify(res));
						uni.showModal({
							content:"" + res.errMsg
						});
						reject(res)
						//typeof param.fail == "function" && param.fail(e.data);
					},
					complete: () => {
						console.log("网络请求complete");
						if (showLoading) {
							uni.hideLoading();
						}
						//typeof param.complete == "function" && param.complete();
					}
				})
			})
		}
	}
})

export default store
